﻿
Imports System.Threading
Imports osi.root.constants
Imports osi.root.lock
Imports osi.root.connector
Imports osi.root.envs

Public Class qless2(Of T)
    Private ReadOnly q As slimqless2(Of T)
    Private _size As Int32

    Public Sub New()
        q = New slimqless2(Of T)()
        _size = 0
    End Sub

    Public Function empty() As Boolean
        Return size() = uint32_0
    End Function

    Public Function size() As UInt32
        '< 0 is in partial of pop operation
        Dim v As Int32 = 0
        v = _size
        Return If(v < 0, uint32_0, CUInt(v))
    End Function

    Public Sub clear()
        While (pop(Nothing))
        End While
    End Sub

    Public Function pop() As T
        Dim o As T = Nothing
        If pop(o) Then
            Return o
        Else
            Return Nothing
        End If
    End Function

    Public Function pop(ByRef d As T) As Boolean
        Return q.pop(d) AndAlso
               k_assert(Interlocked.Decrement(_size) >= 0)
    End Function

    Public Sub push(ByVal d As T)
        emplace(copy_no_error(d))
    End Sub

    Public Sub emplace(ByVal d As T)
        Interlocked.Increment(_size)
        q.emplace(d)
    End Sub

    Public Function push(ByVal d As T, ByVal max_size As UInt32) As Boolean
        Return emplace(copy_no_error(d), max_size)
    End Function

    Public Function emplace(ByVal d As T, ByVal max_size As UInt32) As Boolean
        If Interlocked.Increment(_size) <= max_size Then
            q.emplace(d)
            Return True
        Else
            k_assert(Interlocked.Decrement(_size) >= 0)
            Return False
        End If
    End Function
End Class
